<template>
  <div class="process-definition">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>流程定义列表</span>
          <el-button type="primary" @click="handleUpload">
            <el-icon><Upload /></el-icon>上传流程定义
          </el-button>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="流程名称">
          <el-input v-model="searchForm.name" placeholder="请输入流程名称" />
        </el-form-item>
        <el-form-item label="流程Key">
          <el-input v-model="searchForm.key" placeholder="请输入流程Key" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table :data="tableData" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="180" />
        <el-table-column prop="name" label="流程名称" />
        <el-table-column prop="key" label="流程Key" />
        <el-table-column prop="version" label="版本" width="100" />
        <el-table-column prop="deploymentId" label="部署ID" width="180" />
        <el-table-column prop="resourceName" label="资源名称" />
        <el-table-column label="操作" width="250">
          <template #default="scope">
            <el-button-group>
              <el-button type="primary" size="small" @click="handleStart(scope.row)">
                启动
              </el-button>
              <el-button type="info" size="small" @click="handleView(scope.row)">
                查看
              </el-button>
              <el-button type="danger" size="small" @click="handleDelete(scope.row)">
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 上传对话框 -->
    <el-dialog v-model="uploadDialogVisible" title="上传流程定义" width="500px">
      <el-upload
        class="upload-demo"
        drag
        action="/api/process-definition/upload"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        :before-upload="beforeUpload"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            只能上传 bpmn20.xml 文件
          </div>
        </template>
      </el-upload>
    </el-dialog>

    <!-- 启动流程对话框 -->
    <el-dialog v-model="startDialogVisible" title="启动流程" width="500px">
      <el-form :model="formData">
        <el-form-item label="业务关键字">
          <el-input v-model="formData.businessKey" placeholder="请输入业务关键字" />
        </el-form-item>
        <el-form-item label="变量">
          <el-input v-model="formData.variables" placeholder="请输入变量" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="startDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmStart">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { processDefinitionApi } from '@/api/flowable'

// 搜索表单数据
const searchForm = ref({
  name: '',
  key: ''
})

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 分页数据
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 上传对话框
const uploadDialogVisible = ref(false)

// 启动流程对话框
const startDialogVisible = ref(false)
const currentDefinition = ref({})
const formData = ref({
  businessKey: '',
  variables: {}
})

// 获取流程定义列表
const getProcessDefinitionList = async () => {
  loading.value = true
  try {
    const params = {
      ...searchForm.value,
      page: currentPage.value - 1,
      size: pageSize.value
    }
    const res = await processDefinitionApi.getList(params)
    tableData.value = res.data.data
    total.value = res.data.total
  } catch (error) {
    console.error('获取流程定义列表失败', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getProcessDefinitionList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    name: '',
    key: ''
  }
  handleSearch()
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  getProcessDefinitionList()
}

// 当前页改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  getProcessDefinitionList()
}

// 上传流程定义
const handleUpload = () => {
  uploadDialogVisible.value = true
}

// 上传前校验
const beforeUpload = (file) => {
  const isXML = file.type === 'application/xml'
  if (!isXML) {
    ElMessage.error('只能上传 XML 文件!')
    return false
  }
  return true
}

// 上传成功
const handleUploadSuccess = (response) => {
  ElMessage.success('上传成功')
  uploadDialogVisible.value = false
  getProcessDefinitionList()
}

// 上传失败
const handleUploadError = () => {
  ElMessage.error('上传失败')
}

// 处理启动流程
const handleStart = (row) => {
  currentDefinition.value = row
  formData.value = {
    businessKey: '',
    variables: {}
  }
  startDialogVisible.value = true
}

// 确认启动流程
const confirmStart = async () => {
  try {
    await processDefinitionApi.startInstance(currentDefinition.value.id, formData.value)
    ElMessage.success('流程启动成功')
    startDialogVisible.value = false
  } catch (error) {
    ElMessage.error('流程启动失败')
  }
}

// 查看流程
const handleView = (row) => {
  // TODO: 实现查看流程图的逻辑
}

// 删除流程
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该流程定义吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await processDefinitionApi.delete(row.id)
      ElMessage.success('删除成功')
      getProcessDefinitionList()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

// 处理挂起流程定义
const handleSuspend = (row) => {
  ElMessageBox.confirm('确认挂起该流程定义吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await processDefinitionApi.suspend(row.id)
      ElMessage.success('挂起成功')
      getProcessDefinitionList()
    } catch (error) {
      ElMessage.error('挂起失败')
    }
  })
}

onMounted(() => {
  getProcessDefinitionList()
})
</script>

<style scoped>
.process-definition {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 